﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Webapi.EFCore.Common.Helper;
using Webapi.EFCore.IRepository;
using Webapi.EFCore.IRepository.Base;
using Webapi.EFCore.IService.Base;
using Webapi.EFCore.Model;

namespace Webapi.EFCore.Service.Base
{
    /// <summary>
    /// 服务基类
    /// </summary>
    /// <typeparam name="TEntity"></typeparam>
    public class BaseService<TEntity> where TEntity : class, new()
    {
        private readonly IBaseRepository<TEntity> baseDal;

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="baseRepository"></param>
        public BaseService(IBaseRepository<TEntity> baseRepository)
        {
            baseDal = baseRepository;
        }

        /// <summary>
        /// 写入实体
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public virtual async Task<MessageModel<CurdModel>> Add(TEntity model)
        {
            baseDal.Add(model);
            var result = await baseDal.SaveChangesAsync();
            if (result > 0)
            {
                return HttpResult.Ok();
            }
            else
            {
                return HttpResult.DbError("添加失败!");
            }
        }

        /// <summary>
        /// 获取所有
        /// </summary>
        /// <returns></returns>
        public async Task<List<TEntity>> GetList()
        {
            return await baseDal.GetList();
        }

        /// <summary>
        /// 测试添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task<int> Addint(TEntity model)
        {
            baseDal.Add(model);
            var result = await baseDal.SaveChangesAsync();
            return result;
        }
    }
}
